package com.liu.qqRobot.poke.handler;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.common.content.RedisKeyInterface;
import com.liu.common.utils.HtmlToImageUtils;
import com.liu.common.utils.QQClientUtils;
import com.liu.mybatisPlus.poke.entity.base.Poke;
import com.liu.mybatisPlus.poke.entity.base.PokeGroupUserPoke;
import com.liu.mybatisPlus.poke.service.PokeGroupUserPokeService;
import com.liu.mybatisPlus.poke.service.PokeService;
import com.liu.mybatisPlus.q.service.QGroupUserOperationQuantityService;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.poke.entity.templateParam.EncounterPokeTemplateParam;
import com.liu.qqRobot.q.enums.OperationTypeEnum;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SeekPokeHandler {

    @Resource
    private PokeService pokeService;

    @Resource
    private PokeGroupUserPokeService pokeGroupUserPokeService;

    @Resource
    private QGroupUserOperationQuantityService qGroupUserOperationQuantityService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 处理事件
     * @param data 信息内容
     * @param groupId 群号
     * @param userId 发送人QQ号
     */
    public void handler(EventReportingDTO.Message.Data data, Long groupId, Long userId, Boolean isGroup) {
        if (groupId == 938354542) {
            Object seekPoke = redisTemplate.opsForHash().get(RedisKeyInterface.SEEK_POKE_TIME_REDIS_KEY, groupId + String.valueOf(userId));
            if (seekPoke != null) {
                String existDay = String.valueOf(seekPoke);
                String nowDay = DateUtil.format(DateUtil.offsetHour(DateUtil.date(), 8), "yyyy-MM-dd");
                if (existDay.equals(nowDay)) {
                    return;
                }
            }
            redisTemplate.opsForHash().put(RedisKeyInterface.SEEK_POKE_TIME_REDIS_KEY, groupId + String.valueOf(userId), DateUtil.format(DateUtil.offsetHour(DateUtil.date(), 8), "yyyy-MM-dd"));
        }
        List<Poke> pokeList = pokeService.list();
        int count = 0;
        // 已找到的poke
        List<Poke> encounterPokeList = new ArrayList<>();
        do {
            Poke poke = pokeList.get(RandomUtil.randomInt(pokeList.size()));
            // 判断本次获取的poke是否在已找到的poke中
            if (!encounterPokeList.contains(poke)) {
                QueryWrapper<PokeGroupUserPoke> pokeGroupUserPokeQueryWrapper = new QueryWrapper<>();
                pokeGroupUserPokeQueryWrapper.eq("group_id", groupId);
                pokeGroupUserPokeQueryWrapper.eq("user_id", userId);
                pokeGroupUserPokeQueryWrapper.eq("poke_id", poke.getId());
                pokeGroupUserPokeQueryWrapper.eq("is_release", false);
                PokeGroupUserPoke pokeGroupUserPoke = pokeGroupUserPokeService.getOne(pokeGroupUserPokeQueryWrapper);
                // 判断用户是否已有该poke
                if (pokeGroupUserPoke == null) {
                    encounterPokeList.add(poke);
                    pokeList.remove(poke);
                    count++;
                }
            }
        } while (count <= 2);
        List<EncounterPokeTemplateParam> encounterPokeTemplateParams = new ArrayList<>();
        // 已找到的poke和用户信息做绑定，5分钟过期
        encounterPokeList.forEach(e -> {
            EncounterPokeTemplateParam encounterPokeTemplateParam = new EncounterPokeTemplateParam();
            encounterPokeTemplateParam.setPokeName(e.getName());
            encounterPokeTemplateParam.setAttribute1(e.getAttribute1());
            encounterPokeTemplateParam.setAttribute2(e.getAttribute2());
            encounterPokeTemplateParam.setImgUrl(e.getLocalUrl());
            encounterPokeTemplateParams.add(encounterPokeTemplateParam);
            redisTemplate.opsForValue().set(RedisKeyInterface.ENCOUNTER_POKE_REDIS_KEY + groupId + userId + e.getName(), String.valueOf(e.getId()), 5, TimeUnit.MINUTES);
        });
        Map<String, Object> templateParam = new HashMap<>();
        templateParam.put("pokeList", encounterPokeTemplateParams);
        try {
            HtmlToImageUtils.htmlToImage("encounterPokeTemplate.html", templateParam, "src/main/resources/picture/encounterPoke.png", 3900);
            File file = new File("src/main/resources/picture/encounterPoke.png");
            String encode = Base64.encode(file);
            String msg = "[CQ:at,qq=" + userId + "]\n[CQ:image,file=base64://" + encode+ ",type=show,subType=0]";
            QQClientUtils.sendMsg(msg, userId, groupId, isGroup);
            qGroupUserOperationQuantityService.statisticsOperationQuantityByType(groupId, userId, OperationTypeEnum.SEEK_POKE);
        } catch (IOException | ParserConfigurationException | SAXException | TemplateException e) {
            log.error("获取遇到宝可梦展示模板失败:{}", e.getMessage(), e);
//            QQClientUtils.sendGroupMsg("[CQ:at,qq=" + userId + "]\n获取捕捉宝可梦展示模板失败，请联系制作人", userId, groupId, isGroup);
        }
    }
}
